<script setup lang="ts">
import Taro, { getCurrentInstance, showToast, showLoading, hideLoading, navigateBack } from '@tarojs/taro';
import { reactive, ref, onMounted } from 'vue';
import { useAddrStore, useAuthStore } from '@/store';
import { useNurseUser, use_hospital_dept_bed } from '@/service';
import { useGetAuthInfo } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';

const {
    router: {
        params: { id }
    }
}: any = getCurrentInstance();

// definePageConfig({
//     navigationBarTitleText: id ? '设置地址' : '新增地址'
// });

Taro.setNavigationBarTitle({
    title: id ? '设置地址' : '新增地址'
});

const { getHospitalList, getbedList, getDeptList } = use_hospital_dept_bed();

// const { getLocation } = useweChat_location_service()

const { edit } = useNurseUser();

const { nurseUser } = storeToRefs(useAuthStore());

const { nurseUserAddrList } = nurseUser.value;

const { getProvince, getCity, getCountry } = useAddrStore();

const formData = ref<any>({
    name: '',
    phone: '',
    area: '',
    areaName: '',
    address: '',
    isDefault: '',
    record: '',
    hospital: '',
    hospitalName: '',
    dept: '',
    deptName: '',
    bed: '',
    bedName: '',
    id: '',
    longitude: '',
    latitude: ''
});

const editIndex = ref(nurseUserAddrList?.findIndex(item => item.id == id));

if (editIndex?.value !== undefined && id && nurseUserAddrList) {
    formData.value = { ...nurseUserAddrList[editIndex.value] };
}

onMounted(async () => {
    deptModule.onRefreshOptions();
});

const ruleForm = ref<any>(null);

const select = reactive({ text: '', value: '' });

const defaultChange = () => nurseUserAddrList.forEach(item => (item.isDefault = false));

const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    showLoading({ title: '正在保存...' });
    if (id && editIndex.value !== undefined && nurseUserAddrList) {
        nurseUserAddrList[editIndex.value] = { ...formData.value };
    } else {
        nurseUserAddrList?.push({
            ...formData.value,
            userId: nurseUser.value.id
        });
    }
    const data = { id: nurseUser.value.id, nurseUserAddrList };

    const { error } = await edit(data);

    hideLoading();

    if (!error) {
        showToast({
            title: '保存成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
        setTimeout(() => {
            navigateBack();
        }, 1200);
        useGetAuthInfo();
    }
};
const areaModule: any = reactive({
    show: false,
    province: getProvince,
    city: [{}],
    country: [{}],
    town: [],
    showArea: () => {
        areaModule.show = !areaModule.show;
        if (areaModule.show) {
            select.text = '';
            select.value = '';
        }
    },
    onChange: (item: any) => {
        const { custom, next, value } = item;

        switch (custom) {
            case 'province':
                const city = getCity.filter(item => item.pid == value.id);
                areaModule.city = city;
                break;
            case 'city':
                const country = getCountry.filter(item => item.pid == value.id);
                areaModule.country = country;
                break;
            default:
                break;
        }
        select.text += value.name;
        select.value += `${value.id}-`;
        const name = areaModule[next];
        if (!name?.length) {
            areaModule.show = false;
            formData.value.areaName = select.text;
            formData.value.area = select.value;
        }
    }
});

const hospitalModule = reactive({
    show: false,
    showHospital: () => {
        hospitalModule.show = !hospitalModule.show;

        if (hospitalModule.show) {
            formData.value.hospital = '';
            formData.value.hospitalName = '';
        }
    },
    onChange: (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        formData.value.hospital = item.key;
        formData.value.hospitalName = item.title;
        hospitalModule.show = false;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getHospitalList(pid);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});

const deptModule = reactive({
    show: false,
    showDept: async () => {
        deptModule.show = !deptModule.show;
        if (deptModule.show) {
            formData.value.dept = '';
            formData.value.deptName = '';
            await deptModule.onRefreshOptions();
        }
    },
    options: [],
    onRefreshOptions: async () => {
        const { error, success } = await getDeptList('0', formData.value.hospital);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            deptModule.options = list;
        } else {
            deptModule.options.length = 0;
        }
    },
    onChange: (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        formData.value.dept = item.key;
        formData.value.deptName = item.title;
        deptModule.show = false;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getDeptList(pid, formData.value.hospital);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});

const bedModule: any = reactive({
    show: false,
    columns: [],
    onRefreshColumns: async () => {
        const { error, success } = await getbedList(formData.value.dept);

        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.name
                };
            });
            bedModule.columns = list;
        } else {
            bedModule.columns.length = 0;
        }
    },
    showBed: async () => {
        bedModule.show = !bedModule.show;
        if (bedModule.show) {
            formData.value.bed = '';
            formData.value.bedName = '';
            await bedModule.onRefreshColumns();
        }
    },
    confirm: ({ selectedValue }: any) => {
        formData.value.bed = selectedValue[0].id;
        formData.value.bedName = selectedValue[0].name;
        bedModule.show = false;
    }
});
onMounted(() => {
    // chooseLocation({
    //     success: function (res) {
    //         console.log("res", res);
    //     },
    //     fail: function (res) {
    //         console.log("fail", res);
    //     },
    // });
    // getLocation({
    //     type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
    //     success: function (res) {
    //         const latitude = res.latitude
    //         const longitude = res.longitude
    //         openLocation({
    //             latitude,
    //             longitude,
    //             scale: 18
    //         })
    //     }
    // })
});

// const getLocation = async () => {
//     Taro.getLocation({
//     type: 'wgs84', // 返回可以用于wx.openLocation的经纬度
//     success: function (res) {
//         const { latitude, longitude } = res;
//         console.log('当前位置的纬度：', latitude);
//         console.log('当前位置的经度：', longitude);
//     },
//     fail: function (err) {
//         console.error('获取位置失败', err);
//     }
//     });
//  }

// 打开地图选择位置
const chooseLocation = async () => {
    try {
        let latitude;
        let longitude;
        Taro.getLocation({
            type: 'wgs84',
            // type: 'gcj02',
            success(res) {
                latitude = res.latitude;
                longitude = res.longitude;
                // console.log('获取返回的位置：', res);
            }
        });
        const reschooseLocation = await Taro.chooseLocation({
            latitude, // 39.9,  // 默认纬度
            longitude // 116.4 // 默认经度
        });
        // console.log('选择的位置：', reschooseLocation)
        formData.value.areaName = reschooseLocation.address;
        formData.value.area = reschooseLocation.address;
        formData.value.longitude = reschooseLocation.longitude;
        formData.value.latitude = reschooseLocation.latitude;
    } catch (err) {
        // console.log('选择位置失败：', err)
        formData.value.areaName = '';
        formData.value.area = '';
    }
};
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="id ? '设置地址' : '新增地址'" show-left /> -->
        <view class="w-375px flex-col-center">
            <view class="w-360px">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData">
                    <nut-form-item label="联系人" prop="name" required :rules="[{ required: true, message: '请填写联系人' }]">
                        <nut-input v-model="formData.name" placeholder="请输入联系人" type="text" />
                    </nut-form-item>
                    <nut-form-item label="联系电话" prop="phone" required :rules="[{ required: true, message: '请填写联系电话' }]">
                        <nut-input v-model="formData.phone" placeholder="请输入联系电话" type="text" />
                    </nut-form-item>
                    <nut-form-item label="地区" prop="area" required :rules="[{ required: true, message: '请选择地区' }]">
                        <!-- <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" @click="areaModule.showArea"
                            type="text" /> -->

                        <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" type="text"
                            @click="chooseLocation()" />

                        <!-- <nut-address v-model:visible="areaModule.show" :province="areaModule.province"
                            :city="areaModule.city" :country="areaModule.country" :town="areaModule.town"
                            @change="areaModule.onChange" custom-address-title="请选择所在地区"></nut-address> -->
                    </nut-form-item>
                    <nut-form-item label="详细地址" prop="address" required
                        :rules="[{ required: true, message: '请填写详细地址' }]">
                        <nut-input v-model="formData.address" placeholder="请输入详细地址" type="text" />
                    </nut-form-item>

                    <nut-form-item label="医院" prop="hospital" required :rules="[{ required: true, message: '请选择医院' }]">
                        <nut-input v-model="formData.hospitalName" readonly placeholder="请选择医院" type="text"
                            @click="hospitalModule.showHospital" />
                        <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
                            :title="formData.defaultHospitalName" @change="hospitalModule.onChange" />
                    </nut-form-item>
                    <nut-form-item label="科室" prop="dept" required :rules="[{ required: true, message: '请输入科室' }]">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.deptName" placeholder="请输入科室" type="text" />
                            <nut-button size="mini" type="default" @click="deptModule.showDept">选择科室</nut-button>
                        </view>
                        <basic-dept v-model:visible="deptModule.show" v-model:options="deptModule.options"
                            :lazy-load="deptModule.lazyLoad" :title="formData.defaultHospitalName"
                            @change="deptModule.onChange" />
                    </nut-form-item>
                    <!-- edit by qfx 20250226 prop="" ==> prop="bed"-->
                    <nut-form-item label="床号" prop="bed" :rules="[{ required: true, message: '请输入床号' }]">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.bedName" placeholder="请输入床号" type="text" />
                            <nut-button size="mini" type="default" @click="bedModule.showBed">选择床号</nut-button>
                        </view>
                        <nut-popup v-model:visible="bedModule.show" position="bottom">
                            <nut-picker :columns="bedModule.columns" title="选择床号" @cancel="bedModule.show = false"
                                @confirm="bedModule.confirm" />
                        </nut-popup>
                    </nut-form-item>
                    <nut-form-item label="病历号" prop="record" :rules="[{ required: false, message: '' }]">
                        <nut-input v-model="formData.record" placeholder="请输入病历号" type="text" />
                    </nut-form-item>

                    <nut-form-item label="默认地址" prop="isDefault">
                        <nut-switch v-model="formData.isDefault" @change="defaultChange"></nut-switch>
                    </nut-form-item>
                    <nut-cell>
                        <basic-button text="保存" class="mt-2" @on-click="submit" />
                    </nut-cell>
                </nut-form>
            </view>
        </view>
        <!-- <basic-map /> -->
    </basic-layout>
</template>
